"""
自动选品页面
"""
from PyQt6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QPushButton,
                           QTableWidget, QTableWidgetItem, QLabel, QFrame,
                           QCheckBox, QMessageBox, QDialog, QProgressBar, 
                           QHeaderView, QSpinBox, QComboBox)
from PyQt6.QtCore import Qt, pyqtSignal
from typing import List, Dict, Any
from gui.styles.table_style import apply_default_table_style
from gui.widgets.auto_select_dialog import AutoSelectDialog
from gui.widgets.history_analysis_auto_select_dialog import HistoryAnalysisAutoSelectDialog
from gui.widgets.batch_add_task_dialog import BatchAddTaskDialog
from com.db.task_manager import TaskManager
from biz.script_runner import get_script_runner
import json
import datetime
import traceback
from functools import partial  # 导入partial函数
import webbrowser

class HyperlinkLabel(QLabel):
    """可点击的超链接标签"""
    def __init__(self, text, template_id, parent=None):
        super().__init__(parent)
        self.url = f"https://www.youpin898.com/market/goods-list?listType=10&templateId={template_id}&gameId=730"
        self.setText(f'<a href="{self.url}" style="color: #1890ff; text-decoration: none;">{text}</a>')
        self.setTextFormat(Qt.TextFormat.RichText)
        self.setTextInteractionFlags(Qt.TextInteractionFlag.TextBrowserInteraction)
        self.linkActivated.connect(self.open_url)
        
        # 设置样式
        self.setStyleSheet("""
            QLabel {
                padding: 2px;
            }
            QLabel:hover {
                color: #40a9ff;
            }
        """)
        
    def open_url(self, url):
        """在系统默认浏览器中打开URL"""
        webbrowser.open(url)

class AutoSelectPage(QWidget):
    """自动选品页面"""

    # 日志信号
    log_signal = pyqtSignal(str)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.worker = None
        self.progress_dialog = None
        self.selected_commodities = []  # 选中的商品列表
        self.row_checkboxes = []  # 初始化复选框列表
        self.is_selecting = False  # 添加选品状态标志
        self.setup_ui()

    def setup_ui(self):
        """初始化UI"""
        layout = QVBoxLayout()
        layout.setSpacing(10)

        # 顶部按钮区域
        top_frame = QWidget()
        top_layout = QHBoxLayout(top_frame)
        top_layout.setContentsMargins(0, 0, 0, 0)

        # 右侧按钮区域
        right_widget = QWidget()
        right_layout = QHBoxLayout(right_widget)
        right_layout.setContentsMargins(0, 0, 0, 0)
        right_layout.setSpacing(10)

        # self.auto_select_btn = QPushButton("按在售选品")
        # self.auto_select_btn.setStyleSheet("""
        #     QPushButton {
        #         padding: 5px 15px;
        #         background-color: #409eff;
        #         color: white;
        #         border: none;
        #         border-radius: 2px;
        #     }
        #     QPushButton:hover {
        #         background-color: #66b1ff;
        #     }
        # """)
        # self.auto_select_btn.clicked.connect(self.on_auto_select)

        self.history_analysis_btn = QPushButton("开始选品")
        self.history_analysis_btn.setStyleSheet("""
            QPushButton {
                padding: 5px 15px;
                background-color: #409eff;
                color: white;
                border: none;
                border-radius: 2px;
            }
            QPushButton:hover {
                background-color: #66b1ff;
            }
        """)
        self.history_analysis_btn.clicked.connect(self.on_history_analysis)

        self.batch_add_btn = QPushButton("批量添加任务")
        self.batch_add_btn.setEnabled(False)  # 初始禁用
        self.batch_add_btn.clicked.connect(self.on_batch_add)
        self.batch_add_btn.setStyleSheet("""
            QPushButton {
                padding: 5px 15px;
                background-color: #1890ff;
                color: white;
                border: none;
                border-radius: 3px;
            }
            QPushButton:hover {
                background-color: #40a9ff;
            }
            QPushButton:disabled {
                background-color: #bfbfbf;
            }
        """)

        # 清空记录按钮
        self.clear_btn = QPushButton("清空记录")
        self.clear_btn.clicked.connect(self.on_clear_records)
        self.clear_btn.setStyleSheet("""
            QPushButton {
                padding: 5px 15px;
                background-color: #f56c6c;
                color: white;
                border: none;
                border-radius: 3px;
            }
            QPushButton:hover {
                background-color: #f78989;
            }
        """)

        # 添加按钮到布局
        top_layout.addStretch()  # 左侧添加弹性空间
        # top_layout.addWidget(self.auto_select_btn)
        top_layout.addWidget(self.history_analysis_btn)
        top_layout.addWidget(self.batch_add_btn)
        top_layout.addWidget(self.clear_btn)

        # 进度信息区域
        self.progress_frame = QFrame()
        self.progress_frame.setVisible(False)  # 默认隐藏
        self.progress_frame.setStyleSheet("""
            QFrame {
                background-color: #f0f9eb;
                border: 1px solid #e1f3d8;
                border-radius: 4px;
                padding: 10px;
            }
        """)
        progress_layout = QVBoxLayout(self.progress_frame)
        progress_layout.setSpacing(8)
        progress_layout.setContentsMargins(10, 10, 10, 10)

        # 进度条
        self.progress_bar = QProgressBar()
        self.progress_bar.setTextVisible(True)
        self.progress_bar.setStyleSheet("""
            QProgressBar {
                border: 1px solid #e1f3d8;
                border-radius: 2px;
                text-align: center;
                background-color: #ffffff;
                height: 20px;
            }
            QProgressBar::chunk {
                background-color: #67c23a;
            }
        """)

        # 添加到进度信息区域
        progress_layout.addWidget(self.progress_bar)

        # 表格
        self.auto_select_table = QTableWidget()
        self.auto_select_table.setColumnCount(21)  # 增加列数以适应新的字段
        self.auto_select_table.setHorizontalHeaderLabels([
            "选择", 
            "ID", 
            "商品名称", 
            "磨损范围",
            "当前价格",
            "建议捡漏价",
            "理论最高价",
            "目标售价",
            "历史最低价",
            "历史最高价",
            "Steam溢价率",
            "在售数量",
            "投资评分",
            "流动性评分",
            "价格优势评分",
            "稳定性评分",
            "价格紧凑度",
            "波动率",
            "整体趋势",
            "最近趋势",
            "操作"
        ])
        
        # 设置表格的列宽策略
        header = self.auto_select_table.horizontalHeader()
        header.setStyleSheet("""
            QHeaderView::section { 
                padding: 0 5px;
                background-color: #f5f5f5;
            }
        """)
        header.setFixedHeight(40)
        
        # 设置每列的调整模式
        header.setSectionResizeMode(0, QHeaderView.ResizeMode.Fixed)  # 复选框列固定宽度
        header.setSectionResizeMode(1, QHeaderView.ResizeMode.Interactive)  # ID列可手动调整
        header.setSectionResizeMode(2, QHeaderView.ResizeMode.ResizeToContents)  # 商品名称列自适应内容
        # 其他列自适应内容
        for i in range(3, 20):
            header.setSectionResizeMode(i, QHeaderView.ResizeMode.ResizeToContents)
        header.setSectionResizeMode(20, QHeaderView.ResizeMode.Fixed)  # 操作列固定宽度
        
        # 创建表头复选框容器
        header_widget = QWidget()
        header_layout = QHBoxLayout(header_widget)
        header_layout.setContentsMargins(0, 0, 0, 0)
        header_layout.setSpacing(0)
        header_layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
        
        # 创建表头复选框
        self.header_checkbox = QCheckBox()
        self.header_checkbox.setStyleSheet("""
            QCheckBox {
                margin: 0;
                padding: 0;
            }
            QCheckBox::indicator {
                width: 16px;
                height: 16px;
            }
            QCheckBox::indicator:unchecked {
                border: 1px solid #d9d9d9;
                background-color: white;
            }
            QCheckBox::indicator:checked {
                border: 1px solid #1890ff;
                background-color: #1890ff;
            }
        """)
        self.header_checkbox.clicked.connect(self.on_header_checkbox_changed)  # 改用clicked信号
        header_layout.addWidget(self.header_checkbox)
        
        # 设置表头第一列的widget
        self.auto_select_table.setHorizontalHeaderItem(0, QTableWidgetItem(""))
        header_widget.setFixedSize(50, 40)
        header_widget.setParent(header)
        header_widget.move(header.sectionPosition(0), 0)
        header_widget.show()
        
        layout.addWidget(top_frame)
        layout.addWidget(self.progress_frame)
        layout.addWidget(self.auto_select_table)

        self.setLayout(layout)

    def update_progress_info(self, params: dict):
        """更新进度信息"""
        self.wear_label.setText(f"外观：{params.get('wear')} ({params.get('min_wear', 0):.3f}-{params.get('max_wear', 1):.3f})")
        self.price_label.setText(f"价格：{params.get('min_price', 0):.2f}-{params.get('max_price', 100):.2f}")
        self.premium_label.setText(f"溢价率：{params.get('premium_rate', 0)}%")
        self.count_label.setText(f"最小在售数量：{params.get('min_count', 0)}")

    # def on_auto_select(self):
    #     """点击自动选品按钮"""
    #     # 先停止所有运行中的脚本
    #     script_runner = get_script_runner()
    #     if script_runner.is_running():
    #         script_runner.stop_all()
    #         self.log("已停止所有运行中的脚本")
            
    #     print("AutoSelectPage: 显示自动选品对话框")
    #     dialog = AutoSelectDialog(self)
    #     if dialog.exec() == QDialog.DialogCode.Accepted:
    #         # 获取创建的 worker
    #         self.worker = dialog.get_worker()
            
    #         # 连接信号
    #         self.worker.finished.connect(self.on_select_finished)
    #         self.worker.error.connect(self.on_select_error)
    #         self.worker.progress.connect(self.on_progress_update)
    #         self.worker.result.connect(self.on_result_update)
    #         self.worker.log.connect(self.log)
            
    #         # 更新界面状态
    #         self.progress_frame.setVisible(True)
    #         self.auto_select_btn.setEnabled(False)
    #         self.update_progress_info(dialog.get_values())
            
    #         # 开始选品
    #         self.worker.start()

    def on_select_finished(self):
        """选品完成"""
        # self.auto_select_btn.setEnabled(True)
        self.worker = None
        self.is_selecting = False
        self.history_analysis_btn.setText("开始选品")
        self.progress_bar.setFormat("选品完成")
        self.progress_bar.setValue(100)

    def on_select_error(self, error_msg: str):
        """选品出错"""
        self.progress_frame.setVisible(False)
        # self.auto_select_btn.setEnabled(True)
        self.worker = None
        self.is_selecting = False
        self.history_analysis_btn.setText("开始选品")
        self.progress_bar.setValue(0)  # 重置进度条
        self.progress_bar.setFormat("正在选品，进度【 0/0 (0%)】")

    def on_progress_update(self, current: int, total: int):
        """更新进度"""
        if total > 0:
            # 计算百分比
            percentage = int((current / total) * 100)
            self.progress_bar.setMaximum(100)
            self.progress_bar.setValue(percentage)
            
            # 更新进度文本
            self.progress_bar.setFormat(f"正在选品，进度【 {current}/{total} ({percentage}%)】")

    def on_result_update(self, commodities: List[Dict[str, Any]]):
        """更新结果表格"""
        for commodity in commodities:
            row = self.auto_select_table.rowCount()
            self.auto_select_table.insertRow(row)
            
            # 添加复选框
            checkbox = QCheckBox()
            checkbox.setStyleSheet("""
                QCheckBox {
                    margin: 0;
                    padding: 0;
                }
                QCheckBox::indicator {
                    width: 16px;
                    height: 16px;
                }
                QCheckBox::indicator:unchecked {
                    border: 1px solid #d9d9d9;
                    background-color: white;
                }
                QCheckBox::indicator:checked {
                    border: 1px solid #1890ff;
                    background-color: #1890ff;
                }
            """)
            checkbox.clicked.connect(self.on_row_checkbox_changed)
            
            # 创建容器并设置布局
            container = QWidget()
            layout = QHBoxLayout(container)
            layout.setContentsMargins(0, 0, 0, 0)
            layout.setSpacing(0)
            layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
            layout.addWidget(checkbox)
            
            self.auto_select_table.setCellWidget(row, 0, container)
            self.row_checkboxes.append(checkbox)
            
            # 添加商品信息到表格
            template_id = commodity.get("template_id", "")
            name = commodity.get("name", "")
            wear = commodity.get("wear", "")
            price = commodity.get("price", "")
            suggested_snipe_price = commodity.get("suggested_snipe_price", "")
            theoretical_max_price = commodity.get("theoretical_max_buy_price", "")
            target_sell_price = commodity.get("target_sell_price", "")
            
            # 获取价格分析结果
            # price_analysis = commodity.get('price_analysis', {})
            historical_price_range = commodity.get('historical_price_range', {})
            print(historical_price_range)
            if isinstance(historical_price_range, dict):
                lowest_price = historical_price_range.get('lowest_price', '')
                highest_price = historical_price_range.get('highest_price', '')
            else:
                lowest_price = ''
                highest_price = ''
                
            price_range_compactness = commodity.get('price_range_compactness', '').replace('%', '')  # 移除已有的百分号
            volatility = commodity.get('volatility', '').replace('%', '')  # 移除已有的百分号
            trend_analysis = commodity.get('trend_analysis', {})
            overall_trend = trend_analysis.get('overall_trend', '')
            recent_trend = trend_analysis.get('recent_trend', '')
            
            # 格式化价格数据
            try:
                lowest_price_str = f"{float(lowest_price):.2f}" if lowest_price else ''
                highest_price_str = f"{float(highest_price):.2f}" if highest_price else ''
            except (ValueError, TypeError):
                lowest_price_str = ''
                highest_price_str = ''
            
            # 格式化百分比数据
            try:
                price_range_compactness_str = f"{float(price_range_compactness):.1f}%" if price_range_compactness else ''
                volatility_str = f"{float(volatility):.1f}%" if volatility else ''
                overall_trend_str = str(overall_trend) if overall_trend else ''
                recent_trend_str = str(recent_trend) if recent_trend else ''
            except (ValueError, TypeError):
                price_range_compactness_str = ''
                volatility_str = ''
                overall_trend_str = ''
                recent_trend_str = ''
            
            steam_premium = commodity.get("steam_premium", "")
            count = commodity.get("count", "")
            score = commodity.get("score", "")
            liquidity_score = commodity.get("liquidity_score", "")
            price_advantage_score = commodity.get("price_advantage_score", "")
            stability_score = commodity.get("stability_score", "")
            
            # 创建表格项并设置对齐方式
            id_item = QTableWidgetItem(str(template_id))
            id_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            name_item = QTableWidgetItem(str(name))
            name_item.setTextAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
            wear_item = QTableWidgetItem(str(wear))
            wear_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            price_item = QTableWidgetItem(str(price))
            price_item.setTextAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
            snipe_price_item = QTableWidgetItem(str(suggested_snipe_price))
            snipe_price_item.setTextAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
            max_price_item = QTableWidgetItem(str(theoretical_max_price))
            max_price_item.setTextAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
            target_price_item = QTableWidgetItem(str(target_sell_price))
            target_price_item.setTextAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
            lowest_price_item = QTableWidgetItem(lowest_price_str)
            lowest_price_item.setTextAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
            highest_price_item = QTableWidgetItem(highest_price_str)
            highest_price_item.setTextAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
            premium_item = QTableWidgetItem(str(steam_premium))
            premium_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            count_item = QTableWidgetItem(str(count))
            count_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            score_item = QTableWidgetItem(str(score))
            score_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            liquidity_item = QTableWidgetItem(str(liquidity_score))
            liquidity_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            price_advantage_item = QTableWidgetItem(str(price_advantage_score))
            price_advantage_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            stability_item = QTableWidgetItem(str(stability_score))
            stability_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            compactness_item = QTableWidgetItem(price_range_compactness_str)
            compactness_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            volatility_item = QTableWidgetItem(volatility_str)
            volatility_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            
            # 创建趋势项
            trend_item = QTableWidgetItem(overall_trend_str)
            trend_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            recent_trend_item = QTableWidgetItem(recent_trend_str)
            recent_trend_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            
            # 设置表格项
            self.auto_select_table.setItem(row, 1, id_item)
            name_container = QWidget()
            name_layout = QHBoxLayout(name_container)
            name_layout.setContentsMargins(5, 0, 5, 0)
            name_layout.setSpacing(0)
            name_label = HyperlinkLabel(name, template_id)
            name_layout.addWidget(name_label)
            name_layout.addStretch()
            self.auto_select_table.setCellWidget(row, 2, name_container)
            self.auto_select_table.setItem(row, 3, wear_item)
            self.auto_select_table.setItem(row, 4, price_item)
            self.auto_select_table.setItem(row, 5, snipe_price_item)
            self.auto_select_table.setItem(row, 6, max_price_item)
            self.auto_select_table.setItem(row, 7, target_price_item)
            self.auto_select_table.setItem(row, 8, lowest_price_item)
            self.auto_select_table.setItem(row, 9, highest_price_item)
            self.auto_select_table.setItem(row, 10, premium_item)
            self.auto_select_table.setItem(row, 11, count_item)
            self.auto_select_table.setItem(row, 12, score_item)
            self.auto_select_table.setItem(row, 13, liquidity_item)
            self.auto_select_table.setItem(row, 14, price_advantage_item)
            self.auto_select_table.setItem(row, 15, stability_item)
            self.auto_select_table.setItem(row, 16, compactness_item)
            self.auto_select_table.setItem(row, 17, volatility_item)
            self.auto_select_table.setItem(row, 18, trend_item)
            self.auto_select_table.setItem(row, 19, recent_trend_item)
            
            # 添加操作按钮
            delete_button = QPushButton("删除")
            delete_button.setStyleSheet("""
                QPushButton {
                    padding: 5px 15px;
                    background-color: #f56c6c;
                    color: white;
                    border: none;
                    border-radius: 2px;
                }
                QPushButton:hover {
                    background-color: #f78989;
                }
            """)
            # 使用商品ID来标识要删除的行
            goods_id = str(template_id)
            delete_button.clicked.connect(lambda checked, gid=goods_id: self.on_delete_commodity(gid))
            self.auto_select_table.setCellWidget(row, 20, delete_button)
            
            # 保存商品信息
            self.selected_commodities.append(commodity)

    def on_header_checkbox_changed(self):
        """表头复选框状态改变"""
        state = self.header_checkbox.checkState()
        
        # 只在完全选中或完全未选中时改变行复选框状态
        if state != Qt.CheckState.PartiallyChecked:
            checked = (state == Qt.CheckState.Checked)
            # 阻止行复选框的信号
            for checkbox in self.row_checkboxes:
                checkbox.blockSignals(True)
                checkbox.setChecked(checked)
                checkbox.blockSignals(False)
            
            # 更新批量添加按钮状态
            self.batch_add_btn.setEnabled(checked)

    def on_row_checkbox_changed(self):
        """行复选框状态改变"""
        checked_count = sum(1 for checkbox in self.row_checkboxes if checkbox.isChecked())
        total_count = len(self.row_checkboxes)
        
        # 阻止表头复选框的信号
        self.header_checkbox.blockSignals(True)
        
        if checked_count == 0:
            self.header_checkbox.setCheckState(Qt.CheckState.Unchecked)
        elif checked_count == total_count:
            self.header_checkbox.setCheckState(Qt.CheckState.Checked)
        else:
            self.header_checkbox.setCheckState(Qt.CheckState.PartiallyChecked)
            
        self.header_checkbox.blockSignals(False)

        # 根据选中数量更新批量添加按钮状态
        self.batch_add_btn.setEnabled(checked_count > 0)

    def get_selected_rows(self) -> list:
        """获取选中的行索引列表"""
        return [i for i, checkbox in enumerate(self.row_checkboxes) if checkbox.isChecked()]

    def on_delete_commodity(self, goods_id: str):
        """删除商品"""
        # 查找对应商品ID的行
        row = -1
        for i in range(self.auto_select_table.rowCount()):
            if self.auto_select_table.item(i, 1).text() == goods_id:
                row = i
                break
                
        if row == -1:
            return
            
        # 获取商品名称
        name = self.auto_select_table.cellWidget(row, 2).findChild(HyperlinkLabel).text()
        
        # 确认删除
        reply = QMessageBox.question(
            self,
            "确认删除",
            f"确定要删除商品 [{name}] 吗？",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
            QMessageBox.StandardButton.No
        )
        
        if reply == QMessageBox.StandardButton.Yes:
            # 删除表格行
            self.auto_select_table.removeRow(row)
            # 删除复选框
            self.row_checkboxes.pop(row)
            # 删除商品数据
            self.selected_commodities.pop(row)
            # 更新表头复选框状态
            self.on_row_checkbox_changed()

    def on_add_commodity(self, row: int):
        """添加商品到任务"""
        # 获取当前行的商品信息
        commodity = {
            'template_id': self.auto_select_table.item(row, 1).text(),  # ID列
            'name': self.auto_select_table.cellWidget(row, 2).findChild(HyperlinkLabel).text(),  # 商品名称列
            'wear': self.auto_select_table.item(row, 3).text(),
            'price': self.auto_select_table.item(row, 4).text(),
            'target_price': self.auto_select_table.item(row, 5).text(),
            'premium_rate': self.auto_select_table.item(row, 6).text(),
            'count': self.auto_select_table.item(row, 7).text()
        }

        # 弹出添加任务对话框
        dialog = AddTaskDialog(commodity, self)
        if dialog.exec() == AddTaskDialog.DialogCode.Accepted:
            values = dialog.get_values()

            try:
                # 准备任务数据
                now = int(datetime.now().timestamp() * 1000)
                task_data = {
                    'goods_id': commodity['template_id'],
                    'name': commodity['name'],
                    'sell_min_price': 0,  # 不设置卖出价格
                    'tags': json.dumps([]),  # 空标签
                    'filter_conf': json.dumps({
                        'min_wear': commodity['wear'].split('-')[0],
                        'max_wear': commodity['wear'].split('-')[1]
                    }),
                    'buy_price_limit': values['buy_price_limit'],
                    'buy_num_limit': values['buy_num_limit'],
                    'min_interval': values['min_interval'],
                    'status': 1,  # 启用状态
                    'goods_url': f'https://www.youpin898.com/goodsDetail?id={commodity["template_id"]}',
                    'create_at': str(now),
                    'update_at': now
                }

                # 添加任务
                task_manager = TaskManager()
                task_id = task_manager.add_task(task_data)

                if task_id:
                    QMessageBox.information(self, "提示", "添加任务成功")
                else:
                    QMessageBox.warning(self, "警告", "添加任务失败")

            except Exception as e:
                QMessageBox.critical(self, "错误", f"添加任务时发生错误: {str(e)}")

    def on_batch_add(self):
        """批量添加任务"""
        selected_rows = self.get_selected_rows()
        if not selected_rows:
            QMessageBox.warning(self, "提示", "请先选择要添加的商品")
            return

        selected_items = []
        for row in selected_rows:
            try:
                template_id = self.auto_select_table.item(row, 1).text()  # ID列
                # 从selected_commodities中获取完整数据
                full_data = None
                for item in self.selected_commodities:
                    if str(item.get('template_id')) == template_id:
                        print(f"找到商品 {template_id} 的完整数据")
                        selected_items.append(item)
                        full_data = item
                        break
                
                if not full_data:
                    print(f"警告：未找到商品 {template_id} 的完整数据")
                    
            except Exception as e:
                print(f"处理第 {row} 行数据时出错: {str(e)}")
                print(f"错误详情: {e.__class__.__name__}: {str(e)}")
                import traceback
                print(traceback.format_exc())

        print(f"处理完成的商品数: {len(selected_items)}")
        if selected_items:
            # 打印第一个商品的数据结构，用于调试
            print("商品数据示例:")
            print(json.dumps(selected_items[0], ensure_ascii=False, indent=2))
            
            dialog = BatchAddTaskDialog(selected_items)
            dialog.exec()
        else:
            QMessageBox.warning(self, "提示", "没有有效的商品数据")

    def on_clear_records(self):
        """清空记录"""
        if self.auto_select_table.rowCount() == 0:
            return
            
        # 确认清空
        reply = QMessageBox.question(
            self,
            "确认清空",
            "确定要清空所有记录吗？",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
            QMessageBox.StandardButton.No
        )
        
        if reply == QMessageBox.StandardButton.Yes:
            # 清空表格
            self.auto_select_table.setRowCount(0)
            # 清空复选框列表
            self.row_checkboxes.clear()
            # 清空商品数据
            self.selected_commodities.clear()
            # 重置表头复选框
            self.header_checkbox.setCheckState(Qt.CheckState.Unchecked)
            # 禁用批量添加按钮
            self.batch_add_btn.setEnabled(False)

    def on_history_analysis(self):
        """点击历史分析选品按钮"""
        if self.is_selecting:
            # 如果正在选品，则停止选品
            if self.worker:
                self.worker.stop()  # 停止工作线程
                return
            
        # 开始新的选品
        dialog = HistoryAnalysisAutoSelectDialog(self)
        if dialog.exec() == QDialog.DialogCode.Accepted:
            # 重置进度条
            self.progress_bar.setValue(0)
            self.progress_bar.setFormat("正在选品，进度【 0/0 (0%)】")
            
            # 获取 worker
            self.worker = dialog.get_worker()
            
            # 连接信号
            self.worker.log.connect(self.log)
            self.worker.progress.connect(self.on_progress_update)
            self.worker.result.connect(self.on_result_update)
            self.worker.error.connect(self.on_select_error)
            self.worker.finished.connect(self.on_select_finished)
            self.worker.stopped.connect(self.on_select_stopped)  # 连接停止信号
            
            # 显示进度信息区域
            self.progress_frame.setVisible(True)
            
            # 更新按钮状态
            self.is_selecting = True
            self.history_analysis_btn.setText("停止选品")
            
            # 开始执行
            self.worker.start()

    def on_select_stopped(self):
        """选品被停止"""
        self.worker = None
        self.is_selecting = False
        self.history_analysis_btn.setText("开始选品")
        self.progress_frame.setVisible(False)
        self.progress_bar.setValue(0)  # 重置进度条
        self.progress_bar.setFormat("正在选品，进度【 0/0 (0%)】")
        self.log("选品已停止")

    def log(self, message: str):
        """发送日志消息"""
        try:
            self.log_signal.emit(message)
        except:
            print(message)

    def load_data(self):
        """加载数据（占位）"""
        pass
